package com.msl.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.msl.MslApp;
import com.msl.R;
import com.msl.adapter.ProductckrAdapter;
import com.msl.base.BaseFragment;
import com.msl.bean.AbDcodeBean;
import com.msl.bean.AbStateBean;
import com.msl.bean.AbfBean;
import com.msl.dialog.ERPDialog;
import com.msl.tool.ToastUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class FragmentWWSH1 extends BaseFragment {
    String tag = "FragmentWWSH1";
    protected View mView = null;
    @Bind(R.id.tvs)
    TextView tvs;
    @Bind(R.id.etcode)
    EditText etcode;
    @Bind(R.id.bt)
    Button bt;
    @Bind(R.id.ll)
    LinearLayout ll;
    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.iv1)
    ImageView iv1;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.iv2)
    ImageView iv2;
    @Bind(R.id.tv2)
    TextView tv2;
    @Bind(R.id.rl)
    RelativeLayout rl;
    @Bind(R.id.list)
    ListView list;
    private AbStateBean abStateBean;
    private List<AbStateBean.Data> listdata = new ArrayList<AbStateBean.Data>();
    private ProductckrAdapter sa;
    private boolean flag=false;
    private AbDcodeBean abDcodeBean = new AbDcodeBean();
    private List<AbDcodeBean.DataBean> abDcodeBean1;
    private int index = 0;
    private String  res = "";
    private String  msgg = "";
    private Thread mThread = null;

    protected BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(MslApp.datacc))
            {
                if(MslApp.id1.length()==0 || MslApp.id2.length()==0 || MslApp.id3.length()==0)
                {
                    ToastUtils.showSingleToast(getContext(),"基础信息为空 手输数量失败");
                    return;
                }
                mThread = new Thread()
                    {
                        @Override
                        public void run() {
                            handler.sendEmptyMessage(2);
                            for (int i = 0; i <abDcodeBean.getData().size() ; i++) {
                                snumSync(MslApp.url+"?action=UpdateCodes_Deatil&cid="+MslApp.sSharedPreferences.getString(MslApp.cidk,"")
                                        +"&userID="+MslApp.sSharedPreferences.getInt(MslApp.userID,0)
                                        +"&storeID="+MslApp.sSharedPreferences.getInt(MslApp.storeID,0)
                                        +"&billcode="+abDcodeBean.getData().get(i).getBillcode()
                                        +"&productID="+abDcodeBean.getData().get(i).getProductID()
                                        +"&codeType="+"-1"
                                        +"&codes="+""
                                        +"&manualNums="+abDcodeBean.getData().get(i).getManualNums()
                                        +"&subBillCode="+abDcodeBean.getData().get(i).getSubBillCode().replace("+","%2B")
                                        +"&storeInfo="+MslApp.id1
                                        +"&storeOtherInfo="+MslApp.id1
                                        +"&billChangeType="+MslApp.id2
                                        +"&transactionCode="+MslApp.id3);
                            }
                            updatecodeSync(MslApp.url+"?action=SubmitBill&cid="+MslApp.sSharedPreferences.getString(MslApp.cidk,"")
                                    +"&userID="+MslApp.sSharedPreferences.getInt(MslApp.userID,0)
                                    +"&storeID="+MslApp.sSharedPreferences.getInt(MslApp.storeID,0)
                                    +"&billcode="+abDcodeBean.getData().get(0).getBillcode()
                                    +"&billType="+"121");
                            handler.sendEmptyMessage(3);
                        }
                    };
               mThread.start();
            }
            else if(intent.getAction().equals("netcsucc"))
            {
                tvs.setText("网络状态:正常");
            }
            else if(intent.getAction().equals("netcfail"))
            {
                tvs.setText("网络状态:异常");
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragmentwwsh1, null);
        ButterKnife.bind(this, mView);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MslApp.datacc);
        intentFilter.addAction("netcsucc");
        intentFilter.addAction("netcfail");
        getActivity().registerReceiver(mBroadcastReceiver,intentFilter);
        client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .connectTimeout(90, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(90, TimeUnit.SECONDS)//设置读取超时时间
                .build();

//        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//        try {
//            Class<EditText> cls = EditText.class;
//            Method setShowSoftInputOnFocus;
//            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus",
//                    boolean.class);
//            setShowSoftInputOnFocus.setAccessible(true);
//            setShowSoftInputOnFocus.invoke(etcode, false);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        abDcodeBean = (AbDcodeBean)getActivity().getIntent().getSerializableExtra(MslApp.codedea);
        abDcodeBean1= abDcodeBean.getData();
        sa = new ProductckrAdapter(getContext(),abDcodeBean1);
        list.setAdapter(sa);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sa.setSelectedPosition(position);
                sa.notifyDataSetInvalidated();
                index = position;
            }
        });
        return mView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        getActivity().unregisterReceiver(mBroadcastReceiver);
        if(mThread!=null)
        {
            mThread.interrupt();
            mThread = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @OnClick({R.id.bt, R.id.iv1, R.id.tv1, R.id.iv2, R.id.tv2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt:
                String code = etcode.getText().toString();
                if(code.length()==0)
                {
                    ToastUtils.showSingleToast(getContext(),"请输入数字");
                    return;
                }
                if(MslApp.id1.length()==0|| MslApp.id2.length()==0||MslApp.id3.length()==0)
                {
                    ToastUtils.showSingleToast(getContext(),"请选择基础信息");
                    return;
                }
                if(Integer.parseInt(code)>abDcodeBean.getData().get(index).getyScanNums())
                {
                    ToastUtils.showSingleToast(getContext(),"输入数字超过实际数量");
                    return;
                }
                abDcodeBean.getData().get(index).setManualNums(Integer.parseInt(etcode.getText().toString()));
                abDcodeBean1=abDcodeBean.getData();
                sa = new ProductckrAdapter(getContext(),abDcodeBean1);
                list.setAdapter(sa);
                etcode.setText("");
                break;
            case R.id.iv1:
                flag=false;
                iv1.setImageResource(R.mipmap.u107);
                iv2.setImageResource(R.mipmap.u108);
                break;
            case R.id.tv1:
                flag=false;
                iv1.setImageResource(R.mipmap.u107);
                iv2.setImageResource(R.mipmap.u108);
                break;
            case R.id.iv2:
                flag=true;
                iv1.setImageResource(R.mipmap.u108);
                iv2.setImageResource(R.mipmap.u107);
                break;
            case R.id.tv2:
                flag=true;
                iv1.setImageResource(R.mipmap.u108);
                iv2.setImageResource(R.mipmap.u107);
                break;
        }
    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    if(waitDialog==null)
                    {
                        return;
                    }
                    waitDialog.show();
                    break;
                case 3:
                    if(waitDialog==null)
                    {
                        return;
                    }
                    waitDialog.dismiss();
                    break;
                case 4:
                    ToastUtils.showShort(getActivity(),msgg);
                    break;
                case 5:
                    try {
                        ToastUtils.showShort(getActivity(),msgg);
                        AbfBean ab11 = gson.fromJson(res, AbfBean.class);
                        ERPDialog nDialog1 = new ERPDialog(getActivity(), R.style.Dialog1, new ERPDialog.PriorityListener() {
                            @Override
                            public void finishActivity() {
                                getActivity().finish();
                            }
                        }, ab11.getData().getcallbackID());
                        WindowManager.LayoutParams lp1 = nDialog1.getWindow().getAttributes();
                        lp1.gravity = Gravity.CENTER;
                        nDialog1.setCanceledOnTouchOutside(false);
                        nDialog1.show();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        msgg ="同步单据失败";
                        ToastUtils.showShort(getActivity(),msgg);
                    }
                    break;
                default:
                    break;

            }
        }
    };

    void snumSync(String url)
    {
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    void updatecodeSync(String url)
    {
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            res = response.body().string();
            if (response.isSuccessful()) {
                msgg ="提交完成";
                handler.sendEmptyMessage(5);
            }
            else
            {
                msgg ="同步单据失败";
                handler.sendEmptyMessage(4);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            msgg ="同步单据失败";
            handler.sendEmptyMessage(4);
        }
    }

}
